package com.tofine.smarthome.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.activeandroid.query.Select;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.soundcloud.android.crop.Crop;
import com.squareup.picasso.Picasso;
import com.tofine.smarthome.R;
import com.tofine.smarthome.base.BaseActivity;
import com.tofine.smarthome.model.Device;
import com.tofine.smarthome.model.Scene;
import com.tofine.smarthome.model.SceneDevice;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author ddMax
 * @since 2016/5/31 0:12
 * 说明：添加情景Activity
 */
public class SceneAddActivity extends BaseActivity {
    public static final String TAG = SceneAddActivity.class.getSimpleName();

    public static final int ACTION_CHOOSE_ICON = 0;
    public static final int ACTION_CHOOSE_DEVICE = 1;

    @Bind(R.id.et_scene_name) MaterialEditText mEtSceneName;
    @Bind(R.id.item_scene_image) RelativeLayout mItemSceneImage;
    @Bind(R.id.scene_image) ImageView mSceneImage;
    @Bind(R.id.scene_image_add_icon) ImageView mSceneImageAddIcon;
    @Bind(R.id.item_scene_devices) RelativeLayout mItemSceneDevices;
    @Bind(R.id.scene_list) RecyclerView mSelectedDeviceList;
    @Bind(R.id.btn_add) AppCompatButton mBtnAdd;

    private SelectedDevicesAdapter mAdapter;
    private List<Device> mSelectedDevices;
    private Uri mSceneImageUri;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scene_add;
    }

    @Override
    protected int getActionBarCustomView() {
        return R.layout.actionbar_info;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.title_activity_scene_add;
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    public void initView() {
        initDeviceList();
    }

    private void initDeviceList() {
        if (mSelectedDevices != null) {
            mAdapter = new SelectedDevicesAdapter(this, mSelectedDevices);
            mSelectedDeviceList.setLayoutManager(new LinearLayoutManager(this));
            mSelectedDeviceList.setAdapter(mAdapter);
        }
    }

    @Override
    public void initData() {

    }

    /**
     * 添加图标点击事件
     */
    @OnClick({R.id.item_scene_image, R.id.item_scene_devices, R.id.btn_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.item_scene_image:
                chooseIcon();
                break;
            case R.id.item_scene_devices:
                chooseDevices();
                break;
            case R.id.btn_add:
                completeAdd();
                break;
            default:
                break;
        }

    }

    private void chooseIcon() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, ACTION_CHOOSE_ICON);
    }

    private void performIconCrop(Uri sourceUri) {
        Uri destUri = Uri.fromFile(new File(getCacheDir(), UUID.randomUUID() + ".png"));
        Crop.of(sourceUri, destUri).asSquare().start(this);
    }

    private void updateIcon(Uri uri) {
        if (uri != null) {
            Picasso.with(this).load(uri).into(mSceneImage);
            this.mSceneImageUri = uri;
        }
    }

    private void chooseDevices() {
        Intent intent = new Intent(this, SceneAddChooseDeviceActivity.class);
        startActivityForResult(intent, ACTION_CHOOSE_DEVICE);
    }

    private void completeAdd() {
        String name = mEtSceneName.getText().toString().trim();
        if (checkPrerequisites(name, mSelectedDevices)) {
            saveScene(mSceneImageUri == null ? null : mSceneImageUri.toString(), name, false);
        }
    }

    private void saveScene(String image, String name, boolean status) {
        // TODO: POST情景
        Scene scene = new Scene(image, name, status);
        scene.save();
        // 创建SceneDevice
        for (Device device : mSelectedDevices) {
            SceneDevice sceneDevice = new SceneDevice(scene,
                    (Device) new Select().from(Device.class).where("name='" + device.name + "'").executeSingle());
            sceneDevice.save();
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("new_scene", scene);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    private boolean checkPrerequisites(String name, List<Device> devices) {
        if (!TextUtils.isEmpty(name)) {
            if (devices != null && devices.size() > 0) {
                return true;
            } else {
                new AlertDialog.Builder(this)
                        .setMessage("您还未选择任何设备")
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .create().show();
                return false;
            }
        } else {
            new AlertDialog.Builder(this)
                    .setMessage("请输入情景名称")
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create().show();
            return false;
        }

    }

    @Override
    @SuppressWarnings("unchecked")
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTION_CHOOSE_ICON:
                if (resultCode == RESULT_OK) {
                    performIconCrop(data.getData());
                }
                break;
            case ACTION_CHOOSE_DEVICE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        mSelectedDevices = (ArrayList<Device>) data.getExtras().getSerializable("selected");
                        this.initDeviceList();
                    }
                }
                break;
            case Crop.REQUEST_CROP:
                updateIcon(Crop.getOutput(data));
                break;
            default:
                break;

        }
    }

    public static class SelectedDevicesAdapter extends RecyclerView.Adapter<SelectedDevicesAdapter.ViewHolder> {
        static class ViewHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.device_item) RelativeLayout mItem;
            @Bind(R.id.device_image) ImageView mDeviceImage;
            @Bind(R.id.device_title) TextView mDeviceTitle;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

        private Context mContext;
        private List<Device> mDataSet;

        public SelectedDevicesAdapter(Context context, List<Device> dataSet) {
            this.mContext = context;
            this.mDataSet = dataSet;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_device_selected, null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            final Device device = mDataSet.get(position);
            // 整个Item点击监听
            holder.mItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, DeviceInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("device", device);
                    bundle.putInt("mode", DeviceInfoActivity.MODE_EDIT);
                    intent.putExtras(bundle);
                    mContext.startActivity(intent);
                }
            });
            // 设备图片
            Picasso.with(mContext).load(Uri.parse(device.image)).into(holder.mDeviceImage);
            // 设备名称
            holder.mDeviceTitle.setText(device.name);
        }

        @Override
        public int getItemCount() {
            return mDataSet.size();
        }
    }
}
